<?php

namespace app\admin\middleware;

use app\common\exception\auth\UnLoginException;
use app\Request;
use Exception;
use think\Middleware;

class Auth extends Middleware
{
    public function handle(Request $request, \Closure $next)
    {
        if ($request->isOptions()) {
            return response([], 200, [], 'json');
        }
        $token = $request->header('V-Token');
        $uid = $request->header('V-Uid');
        $time = $request->header('V-Time');
        if (time() - $time/1000 > 5 * 60) {
            throw new Exception('请求异常，请重试');
        }
        if ($token && $uid) {
            $user = cache('user_'.$uid);
            if (!$user || $user['token']!=$token) {
                throw new UnLoginException();
            }
            $request->user = $user;
        }
        return $next($request);
    }
}